<!DOCTYPE HTML>
<html>

<head>
    <!--meta name="theme-color" content=""-->
    <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
    <title>ShadowSkin</title>
</head>
<noscript>
    <mark style="font-size:60px;color:red;">请使用带JavaScript的浏览器！</mark>
</noscript>

<body onload="load_()//}catch(err){alert(err)}">
    <!--script src="debugger.js"></script-->
    <script src="hframe.js" defer></script>
    <script src="mobs.js"></script>
    <script src="pic.js"></script>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
            /*background:aliceblue;*/
        }

        canvas,
        img {
            image-rendering: pixelated;
            image-rendering: crisp-edges;
        }

        #GUI {
            display: flex;
            flex-flow: column nowrap;
            height: 100%;
            width: 100%;
            overflow: hidden;
        }

        #headbar {
            flex: 8 0px;
            text-align: center;
            background: greenyellow;
            box-shadow: 0px 2px 20px -3px silver;
            border-bottom: 2px solid silver;
            background: yellowgreen;
            text-align: center;
            font-size: 2em;
            font-weight: bold;
            color: white;
            text-shadow: 0px 0px 10px grey;
            line-height: 8vh;
        }

        jsjsks {
            border: 3px solid black;
        }

        #toolbar {
            flex: 4 0px;
            width: 100%;
            display: flex;
            text-align: center;
            padding: 0.5em;
        }

        #toolbar>a {
            /*border-right:0.3em solid yellowgreen;*/
            flex: 1 1 0;
            color: yellowgreen;
        }

        #ctnr {
            flex: 100 0px;
            overflow-y: scroll;
            padding: 2vh 2vw;
            display: flex;
            flex-flow: row wrap;
            justify-content: center;
            align-content: flex-start;
        }

        #ctnr::after {
            content: '';
            flex: auto;
        }

        s-skin {
            border-radius: 15px 15px;
            box-shadow: 0px 5px 50px -10px silver;
            background: white;
            display: inline-flex;
            flex-direction: column;
            justify-content: stretch;
            height: 30%;
            overflow: hidden;
            margin: 1.5% 1.5%;
            flex: 0 0 30%;
        }

        s-skin img {
            margin: auto;
            image-rendering: pixelated;
            display: block;
            height: 150%;
            box-sizing: border-box;
        }

        [dd=head] {
            width: 100%;
            overflow: hidden;
            white-space: nowrap;
            flex: 3 0px;
        }

        [dd=name] {
            line-height: 2em;
            flex: 1 0px;
            font-size: 1.3em;
            background: yellowgreen;
            width: 100%;
            text-align: center;
            color: white;
            font-weight: bold;
            text-overflow: ellipsis;
        }

        h-frame {
            background: white;
        }
    </style>
    <script>
        //测试可用
        window.addEventListener("load", () => {
            try {
                let m = [
                    customElements,
                    HFrame,
                    window.postMessage,
                    localStorage
                ]
                for (let i of m) {
                    if (!i) {
                        alert("浏览器兼容性不足，无法正常使用，请换浏览器！");
                        break;
                    }
                }
            } catch (err) {
                alert("浏览器兼容性不足，无法正常使用，请换浏览器！"
                    + "错误信息\n" + err);
            }
        })
    </script>
    <script>
        let ALARMED;
        let SKINS = [];
        let ALARM_WHEN_QUIT = false;
        window.onbeforeunload = (e) => {
            if (!ALARM_WHEN_QUIT) {
                return;
            }
            return "确实要退出吗？你的工作不会被自动保存"
        }
        class Skin extends HTMLElement {
            constructor(obj, temporary) {
                super();
                if (!temporary) {
                    SKINS.push(this);
                }
                /*this._obj=obj;
                this._model=obj.model;
                this._texture_=obj.texture;
                this._name=obj.name;*/

                this.innerHTML = `
            <div dd="head">
                <img dd="headimg">
            </div>
            <div dd="name"></div>`
                let id;
                function rnd() {
                    return String(Math.random()).slice(8);
                }
                this.editor = {
                    modes: {},
                    pen: {}
                }
                this.setSkin(obj);
                this.addEventListener("click", () => {
                    view(this);
                });
            }


            loadPicture() {
                let cvs = document.createElement("canvas");
                let ctx = cvs.getContext("2d");
                let img = new Image();
                img.src = this.texture;
                img.onload = () => {
                    cvs.width = 16;
                    cvs.height = 32;
                    let mo = mobs[this.model];
                    for (let i in mo) {
                        let {
                            size,
                            uv: [u0, u1],
                            origin: [o1, o2],
                            inflate: inf
                        } = mo[i];
                        let [x, y, z] = size;
                        o2 += size[1];
                        let p = [z + u0, z + u1, x, y];
                        ctx.drawImage(
                            img, p[0], p[1],
                            p[2], p[3], 8 + o1,
                            35 - o2, p[2], p[3]
                        );
                    };
                    this.querySelector("[dd=headimg]").src = cvs.toDataURL();
                }
            }


            set name(v) {
                this.info.name = this._name = v;
                this.querySelector("[dd=name]").innerText = this.name;
            }
            get name() {
                return this._name;
            }


            set texture(v) {
                this.info.texture = this._texture = v;
                this.loadPicture();
            }
            get texture() {
                return this._texture;
            }


            set model(v) {
                this.info.model = this._model = v;
                this.loadPicture();
            }
            get model() {
                return this._model;
            }

            getInfo() {
                return this.info;
            }

            setSkin(o) {
                this.info = o;
                this.name = o.name;
                this.texture = o.texture;
                this.model = o.model;
            }
        }
        try {
            customElements.define("s-skin", Skin);
            //customElements.whenDefined("s-skin").then(load_);
        } catch (err) { alert(err) }

        function ide(n) {
            return document.getElementById(n);
        }

        //处理本地数据
        function handleData(fn, alarm) {
            if (localStorage) {
                let q = localStorage.getItem("powerskin");
                try {
                    q = JSON.parse(q);
                } catch (e) {
                    q = [];
                }
                q = fn(q) || q;
                localStorage.setItem("powerskin", JSON.stringify(q));
                return true;
            }
            if (alarm || !ALARMED) {
                alert("您的浏览器不支持localStorage，强烈建议" +
                    "升级浏览器，否则您的一切工作在刷新后将丢失！");
                ALARMED = true;
            }
            return false;
        }

        function saveData() {
            handleData(() => {
                return SKINS.map(e => {
                    let a = e.getInfo();
                    return a;
                });
            })
        }

        function view(e) {
            let vw = ide("viewer");
            vw.fullScreen = true;
            ALARM_WHEN_QUIT = true;
            let obj = e.info;
            vw.send(obj);
            //保存皮肤
            function recv(d) {
                d = d.detail;
                switch (d.event) {
                    case "close":
                        if (d.save) {
                            save(d.save);
                        }
                        close();
                        break;
                    case "save":
                        save(d.save);
                        break;
                    case "copy":
                        let info = Object.assign({ name: d.name }, e.getInfo());
                        setSkin(info, true);
                        break;
                    case "delete":
                        SKINS.forEach((el, i) => {
                            if (e == el) {
                                SKINS.splice(i, 1);
                                ide("ctnr").removeChild(e);
                                saveData();
                                close();
                            }
                        })
                        break;
                }
                function save(obj) {
                    e.setSkin(d.save);
                    SKINS.forEach((ele, i) => {
                        if (ele == e) {
                            SKINS.splice(i, 1);
                            SKINS.unshift(e);
                        }
                    });
                    let ctnr = ide("ctnr");
                    ctnr.insertBefore(e, ctnr.firstChild);
                    saveData();
                }
                function close() {
                    //某些浏览器在弹出对话框后太快关闭会有bug
                    setTimeout(function () {
                        viewer.fullScreen = false;
                        vw.removeEventListener("msg", recv);
                        ALARM_WHEN_QUIT = false;
                    }, 100);
                }
            }
            vw.addEventListener("msg", recv);
        }

        function load_() {
            /*for(let i=0;i<15;i++){
                let name=(Math.random()*(10**15)).toString(36).slice(0,8);
                setSkin({name:name});
            }*/
            try {
                if (b64sk.raw.creeper) setSkin({
                    name: "creeper",
                    texture: b64sk.raw.creeper,
                    model: "alex"
                });
                setSkin({
                    name: "alex",
                    texture: b64sk.raw.alex,
                    model: "alex"
                });
                setSkin({
                    name: "steve",
                    texture: b64sk.raw.steve,
                    model: "steve"
                });
                handleData((m) => {
                    for (let i in m) {
                        let n = setSkin(m[i]);
                        SKINS.push(n)
                    }
                });
            } catch (err) { alert(err.stack) }
        }

        function importSkin() {
            let fi = ide("loadSkin");
            fi.click();
            fi.onchange = () => {
                let fr = new FileReader();
                let isproj = fi.value.split(".").pop() == "json";
                if (isproj) {
                    fr.onload = () => {
                        let obj = JSON.parse(fr.result);
                        let n = setSkin(obj);
                        SKINS.push(n);
                        saveData();
                    }
                    fr.readAsText(fi.files[0])
                } else {

                    fr.onload = () => {
                        let name = (function () {
                            let n = fi.value;
                            n = n.split("\\").pop();
                            let y = n.split(".");
                            if (y.length >= 2) n = y[y.length - 2];
                            return n.slice(-10);
                        })();
                        setSkin({
                            name: name,
                            texture: fr.result,
                            model: "steve"
                        }, true);
                        fi.value = null;
                    }
                    fr.readAsDataURL(fi.files[0]);
                    fr.onerror = (ev) => {
                        alert("哎唷，读取失败啦！\n" + ev)
                    }
                }

            }
        }

        function createSkin() {
            let n = prompt("请输入新皮肤名字", "New skin");
            if (!n) return;
            setSkin({
                name: n,
                model: "steve",
                texture: b64sk.raw.dummy
            }, true)
        }

        function setSkin(obj, save) {
            let n = new Skin(obj, !save);
            let ctnr = ide("ctnr");
            if (save) {
                ctnr.insertBefore(n, ctnr.firstElementChild);
            } else {
                ctnr.appendChild(n);
            }
            if (save) {
                saveData();
            }
            return n;
        }
    </script>
    <h-frame id="viewer" style="display:none;background:white;" src="viewer2.html"></h-frame>
    <div id="GUI">
        <div id="headbar">ShadowSkin</div>
        <div id="toolbar">
            <a onclick="importSkin()">导入</a>
            <a href="tutorial.html" target="_blank" style="text-shadow:0 0 2px #fafac3;">使用手册</a>
            <a target="_blank" href="https://github.com/Fancyflame/ShadowSkin">github</a>
            <a onclick="createSkin()">新建</a>
        </div>
        <div id="ctnr"></div>
    </div>
    <div style="display:none">
        <input type="file" id="loadSkin">
    </div>
</body>

</html>